package com.bdqn.demo.service;

import com.bdqn.demo.dao.SysUserRepository;
import com.bdqn.demo.pojo.SysUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * SysUserServiceImpl
 *
 * @author LILIBO
 * @since 2021-11-19
 */
@Service("SysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserRepository sysUserRepository;

    @Override
    public List<SysUser> findByUsrName(String usrName) {
        return sysUserRepository.findByUsrName(usrName);
    }

    @Override
    public List<SysUser> findByUsrNameAndUsrPasswordAndUsrRoleIdOrderByUsrId(String usrName, String usrPassword, Long usrRoleId) {
        return sysUserRepository.findByUsrNameAndUsrPasswordAndUsrRoleIdOrderByUsrId(usrName, usrPassword, usrRoleId);
    }

    @Override
    public List<SysUser> findByRoleId(Long roleId) {
        return sysUserRepository.findByRoleId(roleId);
    }

    @Override
    public List<SysUser> findByRoleIdNative(Long roleId) {
        return sysUserRepository.findByRoleIdNative(roleId);
    }

    @Override
    public Page<SysUser> findPageByUsrRoleId(Long roleId, Pageable pageable) {
        return sysUserRepository.findPageByUsrRoleId(roleId, pageable);
    }

    @Override
    public List<SysUser> findByRoleIdParam(Long roleId) {
        return sysUserRepository.findByRoleIdParam(roleId);
    }

    @Override
    public int modifyNameById(String usrName, Long usrId) {
        return sysUserRepository.modifyNameById(usrName, usrId);
    }

    @Override
    public Page<SysUser> findPageByMap(Map param, Pageable pageable) {
        return sysUserRepository.findAll(new Specification<SysUser>() {
            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("usrName") != null) { // 动态SQL
                    predicates.add(cb.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
                }
                if (param.get("roleId") != null) {
                    predicates.add(cb.equal(root.get("usrRoleId"), param.get("roleId")));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
    }

}